<?php
/**
 * @author 
 */
namespace App\Traits;
use Illuminate\Http\Request;
use App\Repositories\AccountRepository;
use App\Repositories\UserRepository;
//登录认证
trait Auth
{

    //-------------------------------------------------------------------------------
    /**
     * 验证登陆
     * 验证session
     */
    public static function isWebLogin(Request $request){
        // if($request->header('token')) {
        //     $res=self::checkWebToken($request);
        //     if(!$res){
        //         return false;
        //     }elseif($res['state']!=2){
        //         return false;
        //     }
        //     session(['userinfo'=>$res]);
        //     return true;
        // }else{
        //      return false;
        // }
        $userinfo=$request->session()->get('userinfo');
        if($userinfo){
            session(['userinfo'=>$userinfo]);
            return true;
        }else{
            return false;
        }
    }
    public static function checkWebToken(Request $request)
    {
        $token=$request->header('token');
        $userRes=new UserRepository();
        $user=$userRes->infoBytoken($token);
        if($user){
            return self::setWebToken($user['id']);
        }
        return false;

    }

    public static function setWebToken($id)
    {
        $newToken=md5(time().rand(1000,9999));
        $userRes=new UserRepository();
        $userinfo=$userRes->info($id);
        $token='';
        if($userinfo){
            $tc=time()-$userinfo['time'];
            if($tc>=86400){
                $upArr=[];
                $upArr['token']=$newToken;
                $upArr['time']=time();
                $upArr['id']=$id;
                $res=$userRes->update($upArr);
                $token= $newToken;
                $userinfo['token']=$token;
                return $userinfo;
            }else{
                return $userinfo;
            }
        }
        return false;
    }
}